<template>
  <div class="upload-file" style="width: 100%">
    <!-- 文件列表 -->
    <transition-group
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul"
    >
      <li
        :key="file.path"
        class="el-upload-list__item ele-upload-list__item-content"
        v-for="(file, index) in fileList"
      >
        <!-- <el-link :href="`${baseUrl}${file.path}`" :underline="false" target="_blank"> -->
        <span class="el-icon-document" @click="downLoadFile(file)">
          {{ file.fileName }}
        </span>
        <!-- </el-link> -->
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger"
            ><svg-icon
              class-name="upload-icon"
              icon-class="remove"
            />删除</el-link
          >
        </div>
      </li>
    </transition-group>
    <el-upload
      multiple="multiple"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :http-request="uploadFile"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :show-file-list="false"
      class="upload-file-uploader"
      ref="fileUpload"
    >
      <!-- 上传按钮 -->
      <el-button class="upload-button" type="primary" size="mini"
        >上传附件</el-button
      >
      <!-- 上传提示 -->
      <!-- <div class="upload__tip" slot="tip" v-if="showTip">
                支持 {{ fileType.join("/") }} 格式，每个文件大小不超过{{ fileSize }}MB
                <p style="color: red">不得上传国家秘密、“内部”“内部资料”等工作秘密材料。</p>
            </div> -->
    </el-upload>
  </div>
</template>

<script>
import { defineComponent, onMounted, reactive, ref, toRefs } from "vue";
import {
  getUploadToken,
  uploadFile,
  getDownloadtoken,
  downloadFile,
} from "@/api/uploadapi";
export default defineComponent({
  name: "",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 3,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 10,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => [
        "gif",
        "jpg",
        "jpeg",
        "png",
        "bmp",
        "txt",
        "doc",
        "xls",
        "pdf",
        "rar",
        "docx",
        "xlsx",
        "wps",
        "zip",
      ],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },
  setup(props, { emit }) {
    const dataMap = reactive({
      baseUrl: "",
      fileList: props.value || [],
    });
    const methodsMap = reactive({
      // 重写上传程序
      async uploadFile(params) {
        let token = await getUploadToken();
        var { file } = params;
        // var formData = new FormData()
        // formData.append("token", data.params.token)
        // formData.append("file", file)
        // let res = await upload(formData)
        // if (res)
        let res = await uploadFile({
          file: file,
          uploadToken: token,
        });
        methodsMap.handleUploadSuccess(res);
      },
      // 上传前校检格式和大小
      async handleBeforeUpload(file) {
        console.log("handleBeforeUpload", file);
        // 校检文件类型
        if (this.fileType) {
          const fileName = file.name.split(".");
          const fileExt = fileName[fileName.length - 1];
          const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
          if (!isTypeOk) {
            this.$modal.msgError(
              `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
            );
            return false;
          }
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        console.log("res");
        return true;
      },
      // 文件个数超出
      handleExceed() {
        this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
      },
      // 上传失败
      handleUploadError(err) {
        this.$modal.msgError("上传文件失败，请重试");
        this.$modal.closeLoading();
      },
      // 上传成功回调
      handleUploadSuccess(res, file) {
        if (res.code == 0) {
          dataMap.fileList.push(res.data);
          emit("update:value", dataMap.fileList);
        }
      },
      // 删除文件
      handleDelete(index) {
        dataMap.fileList.splice(index, 1);
        emit("update:value", dataMap.fileList);
      },
      // 获取文件名称
      getFileName(name) {
        // 如果是url那么取最后的名字 如果不是直接返回
        if (name.lastIndexOf("/") > -1) {
          return name.slice(name.lastIndexOf("/") + 1);
        } else {
          return name;
        }
      },
      async downLoadFile(file) {
        console.log(file);
        let tokenRes = await getDownloadtoken(file.fileId);
        console.log(tokenRes);
        let params = {
          accessToken: tokenRes,
          fileId: file.fileId,
          fileName: file.fileName,
        };
        //  let res = await downloadFile(params);
        //  console.log(res)
        // , downloadFile

        this.download(params, file.fileName);
      },
      // 对象转成指定字符串分隔
      listToString(list, separator) {
        let strs = "";
        separator = separator || ",";
        for (let i in list) {
          strs += list[i].path + separator;
        }
        return strs != "" ? strs.substr(0, strs.length - 1) : "";
      },
    });
    onMounted(() => {});
    return {
      ...toRefs(dataMap),
      ...toRefs(methodsMap),
    };
  },
});
</script>
<style scoped lang="scss">
.upload-button {
}

.upload-icon {
  margin-right: 8px;
  width: 14px;
  height: 14px;
}

.upload__tip {
  font-weight: 400;
  font-size: 12px;
  color: #4e5969;
  line-height: 20px;
  margin-top: 8px;
}

.el-icon-document {
  cursor: pointer;
}

.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  padding-left: 8px;
  background-color: white;
  width: 300px;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
  width: 100%;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
